import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

@WebServlet("/guessNum")
public class GuessNumServlet extends HttpServlet {
    private int ToGuess=0;
    private int count=0;
    private TemplateEngine engine = new TemplateEngine();

    @Override
    public void init() throws ServletException {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(this.getServletContext());
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");

        engine.setTemplateResolver(resolver);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Random random = new Random();
        ToGuess = random.nextInt(100)+1;
        count = 0;

        WebContext context = new WebContext(req,resp,getServletContext());
        context.setVariable("newGame",false);
        engine.process("guess",context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String str = req.getParameter("num");
        int num = Integer.parseInt(str);
        String res = "";
        count++;
        if(num > ToGuess){
            res = "猜大了";
        }else if (num < ToGuess){
            res = "猜小了";
        }else {
            res = "猜对了";
        }

        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("newGame",true);
        webContext.setVariable("result",res);
        webContext.setVariable("count",count);

        engine.process("guess",webContext,resp.getWriter());
    }
}
